import * as qiniu from 'qiniu-js'
import Vue from 'vue'
let vue = new Vue()
const CONFIG = {
  useCdnDomain: true, // 使用cdn加速
  region: qiniu.region.z1 // 华北地区
}
vue.ossConfig = CONFIG
export default {
  ossVue: vue,
  // 上传文件
  createQiniuUploader ({file, putExtra, nextCb, errorCb, completeCb}) {
    this.initBaseConf(baseConf => {
      let _putExtra = putExtra || {
        fname: '',
        params: {'x:tenantId': baseConf.tenantId},
        mimeType: null
      }
      let key = this.getKey(file)
      // console.log('file: ', file)
      // console.log('key: ', key)
      const observable = qiniu.upload(file, key, baseConf.uptoken, _putExtra, vue.ossConfig)
      observable.subscribe({
        next: res => {
          if (nextCb && typeof nextCb === 'function') {
            nextCb(res) // 主要用来展示进度
          }
        },
        error: err => {
          console.log('err', err)
          if (errorCb && typeof errorCb === 'function') {
            errorCb(err)
          }
          if (err.code === 614) {
            vue.$notify.error({
              title: '错误',
              message: '文件已存在，请更换文件名再试'
            })
          } else {
            vue.$notify.error({
              title: '错误',
              message: '上传失败'
            })
          }
        },
        complete: res => {
          if (completeCb && typeof completeCb === 'function') {
            completeCb(res, baseConf)
          }
        }
      })
    })
  },
  // 获取上传凭证和图片存储空间读取域名
  getUptoken () {
    return new Promise((resolve, reject) => {
      let url = '/oss/auth'
      vue.get(url).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取上传域名  http://upload.qiniup.com
  getUploadUrl () {
    return new Promise((resolve, reject) => {
      qiniu.getUploadUrl(CONFIG).then(url => {
        resolve(url)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 初始化七牛云存储的配置
  initBaseConf (cb) {
    let baseConfig = {}
    this.getUptoken()
      .then(res => {
        if (res.data.code === 200) {
          baseConfig.uptoken = res.data.data.uptoken
          baseConfig.domain = res.data.data.domain
          baseConfig.tenantId = res.data.data.tenantId
          return this.getUploadUrl()
        }
      })
      .then(url => {
        baseConfig.url = url
        cb(baseConfig)
      })
      .catch(err => {
        vue.handleError(err)
      })
  },
  // 定义上传文件名
  getKey (file) {
    let header = sessionStorage.getItem('domain_header_tag')
    // 当save_key和unique_names设为false时，该方法将被调用
    let timeStamp = this.getTimeStamp()
    // 根据不同的文件type类型，生成对应的key
    let type = '.'
    // .rar文件
    if (/\.rar$/.test(file.name)) {
      type += 'rar'
    // 图片，视频，音频等多格式文件
    } else if (/^(video|audio|image)/.test(file.type)) {
      type += file.type.split('/')[1] || ''
    // 其他文件类型
    } else {
      switch (file.type) {
        case 'text/plain': type += 'txt'; break
        case 'application/pdf': type += 'pdf'; break
        case 'application/msword': type += 'doc'; break
        case 'application/vnd.ms-excel': type += 'xls'; break
        case 'application/vnd.ms-powerpoint': type += 'ppt'; break
        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': type += 'docx'; break
        case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': type += 'xlsx'; break
        case 'application/vnd.openxmlformats-officedocument.presentationml.presentation': type += 'pptx'; break
        case 'application/x-zip-compressed': type += 'zip'; break
      }
    }
    var key = (header ? (header + '_') : '') + timeStamp + type
    return key
  },
  // 获取时间戳
  getTimeStamp () {
    let now = new Date()
    let Y = now.getFullYear()
    let M = '0' + (now.getMonth() + 1)
    let D = '0' + now.getDate()
    let h = '0' + now.getHours()
    let m = '0' + now.getMinutes()
    let s = '0' + now.getSeconds()
    let ms = '000' + now.getMilliseconds()
    return Y + M.substr(-2) + D.substr(-2) + h.substr(-2) + m.substr(-2) + s.substr(-2) + ms.substr(-4)
  }
}
